<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8">
    <title>智慧小区管理系统</title>
    <meta name="keywords" content="智慧小区,物业管理,社区管理,智能安防,数据分析,便民服务,layui">
    <meta name="description" content="智慧小区管理系统，基于layui的现代化社区管理平台，提升物业管理效率与居民生活质量。">
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta http-equiv="Access-Control-Allow-Origin" content="*">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <link rel="icon" href="images/favicon.ico">
    <link rel="stylesheet" href="lib/layui-v2.6.3/css/layui.css" media="all">
    <link rel="stylesheet" href="css/layuimini.css?v=2.0.4.2" media="all">
    <link rel="stylesheet" href="css/themes/default.css" media="all">
    <link rel="stylesheet" href="lib/font-awesome-4.7.0/css/font-awesome.min.css" media="all">
    <!--[if lt IE 9]>
    <script src="https://cdn.staticfile.org/html5shiv/r29/html5.min.js"></script>
    <script src="https://cdn.staticfile.org/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->
    <style id="layuimini-bg-color">
    </style>
    <!-- AI悬浮窗口样式 -->
    <style>
        #contentDiv {
            white-space: pre-line;  /* 让换行符显示 */
        }

        .ai-float-btn {
            position: fixed;
            bottom: 30px;
            left: 30px;
            width: 60px;
            height: 60px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border-radius: 50%;
            box-shadow: 0 4px 20px rgba(102, 126, 234, 0.4);
            cursor: move;
            z-index: 9999;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.3s ease;
            animation: pulse 2s infinite;
            user-select: none;
        }
        
        .ai-float-btn:hover {
            transform: scale(1.1);
            box-shadow: 0 6px 25px rgba(102, 126, 234, 0.6);
        }
        
        .ai-float-btn:active {
            cursor: grabbing;
        }
        
        .ai-float-btn i {
            color: white;
            font-size: 24px;
            pointer-events: none;
        }
        
        @keyframes pulse {
            0% {
                box-shadow: 0 4px 20px rgba(102, 126, 234, 0.4);
            }
            50% {
                box-shadow: 0 4px 20px rgba(102, 126, 234, 0.8);
            }
            100% {
                box-shadow: 0 4px 20px rgba(102, 126, 234, 0.4);
            }
        }
        
        .ai-chat-window {
            position: fixed;
            width: 700px;
            height: 500px;
            background: white;
            border-radius: 15px;
            box-shadow: 0 10px 40px rgba(0, 0, 0, 0.2);
            z-index: 9998;
            display: none;
            flex-direction: column;
            overflow: hidden;
        }
        
        .ai-chat-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 15px 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            cursor: move;
        }
        
        .ai-chat-header h3 {
            margin: 0;
            font-size: 16px;
            pointer-events: none;
        }
        
        .ai-chat-controls {
            display: flex;
            align-items: center;
            gap: 15px;
        }
        
        .ai-chat-clear, .ai-chat-close {
            cursor: pointer;
            font-size: 16px;
            padding: 5px;
            border-radius: 3px;
            transition: background-color 0.2s;
        }
        
        .ai-chat-clear:hover, .ai-chat-close:hover {
            background-color: rgba(255, 255, 255, 0.2);
        }
        
        .ai-chat-messages {
            flex: 1;
            padding: 15px;
            overflow-y: auto;
            background: #f8f9fa;
        }
        
        .ai-message {
            margin-bottom: 15px;
            display: flex;
            align-items: flex-start;
        }
        
        .ai-message.user {
            justify-content: flex-end;
        }
        
        .ai-message-content {
            max-width: 80%;
            padding: 12px 15px;
            border-radius: 15px;
            word-wrap: break-word;
            position: relative;
        }
        
        .ai-message.user .ai-message-content {
            background: #667eea;
            color: white;
            border-bottom-right-radius: 5px;
        }
        
        .ai-message.ai .ai-message-content {
            background: white;
            color: #333;
            border: 1px solid #e0e0e0;
            border-bottom-left-radius: 5px;
        }
        
        .message-header {
            font-size: 12px;
            margin-bottom: 5px;
            opacity: 0.8;
            font-weight: 500;
        }
        
        .message-text {
            line-height: 1.5;
            margin-bottom: 5px;
        }
        
        .timestamp {
            font-size: 10px;
            opacity: 0.6;
            text-align: right;
        }
        
        .ai-message.user .timestamp {
            text-align: left;
        }
        
        .ai-chat-input {
            padding: 15px;
            border-top: 1px solid #e0e0e0;
            background: white;
        }
        
        .ai-input-group {
            display: flex;
            gap: 10px;
        }
        
        .ai-input-group input {
            flex: 1;
            border: 1px solid #ddd;
            border-radius: 20px;
            padding: 8px 15px;
            outline: none;
        }
        
        .ai-input-group input:focus {
            border-color: #667eea;
        }
        
        .ai-send-btn {
            background: #667eea;
            color: white;
            border: none;
            border-radius: 50%;
            width: 35px;
            height: 35px;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        
        .ai-send-btn:hover {
            background: #5a6fd8;
        }
        
        .ai-loading {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 3px solid #f3f3f3;
            border-top: 3px solid #667eea;
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
    </style>
</head>
<body class="layui-layout-body layuimini-all">
<div class="layui-layout layui-layout-admin">

    <div class="layui-header header">
        <div class="layui-logo layuimini-logo"><img src="images/logo.png" style="height:32px;vertical-align:middle;margin-right:8px;">智慧小区管理系统</div>
        <div class="layuimini-header-content">
            <a>
                <div class="layuimini-tool"><i title="展开" class="fa fa-outdent" data-side-fold="1"></i></div>
            </a>

            <!--电脑端头部菜单-->
            <ul class="layui-nav layui-layout-left layuimini-header-menu layuimini-menu-header-pc layuimini-pc-show">
            </ul>

            <!--手机端头部菜单-->
            <ul class="layui-nav layui-layout-left layuimini-header-menu layuimini-mobile-show">
                <li class="layui-nav-item">
                    <a href="javascript:;"><i class="fa fa-list-ul"></i> 选择模块</a>
                    <dl class="layui-nav-child layuimini-menu-header-mobile">
                    </dl>
                </li>
            </ul>

            <ul class="layui-nav layui-layout-right">

                <li class="layui-nav-item" lay-unselect>
                    <a href="javascript:;" data-refresh="刷新"><i class="fa fa-refresh"></i></a>
                </li>
                <li class="layui-nav-item" lay-unselect>
                    <a href="javascript:;" data-clear="清理" class="layuimini-clear"><i class="fa fa-trash-o"></i></a>
                </li>
                <li class="layui-nav-item mobile layui-hide-xs" lay-unselect>
                    <a href="javascript:;" data-check-screen="full"><i class="fa fa-arrows-alt"></i></a>
                </li>
                <li class="layui-nav-item layuimini-setting">
                    <a href="javascript:;" id="user_name">admin</a>
                    <dl class="layui-nav-child">
                        <dd>
                            <a href="javascript:;" layuimini-content-href="page/user-setting.html" data-title="基本资料" data-icon="fa fa-gears">基本资料<span class="layui-badge-dot"></span></a>
                        </dd>
                        <dd>
                            <a href="javascript:;" layuimini-content-href="page/user-password.html" data-title="修改密码" data-icon="fa fa-gears">修改密码</a>
                        </dd>
                        <dd>
                            <hr>
                        </dd>
                        <dd>
                            <a href="javascript:;" class="login-out">退出登录</a>
                        </dd>
                    </dl>
                </li>
                <li class="layui-nav-item layuimini-select-bgcolor" lay-unselect>
                    <a href="javascript:;" data-bgcolor="配色方案"><i class="fa fa-ellipsis-v"></i></a>
                </li>
            </ul>
        </div>
    </div>

    <!--无限极左侧菜单-->
    <div class="layui-side layui-bg-black layuimini-menu-left">
    </div>

    <!--初始化加载层-->
    <div class="layuimini-loader">
        <div class="layuimini-loader-inner"></div>
    </div>

    <!--手机端遮罩层-->
    <div class="layuimini-make"></div>

    <!-- 移动导航 -->
    <div class="layuimini-site-mobile">
        <li class="layuimini-tab-roll-right layui-icon layui-icon-right"></li>
    </div>

    <div class="layui-body">

        <div class="layuimini-tab layui-tab-rollTool layui-tab" lay-filter="layuiminiTab" lay-allowclose="true">
            <ul class="layui-tab-title">
                <li class="layui-this" id="layuiminiHomeTabId" lay-id=""></li>
            </ul>
            <div class="layui-tab-control">
                <li class="layuimini-tab-roll-left layui-icon layui-icon-left"></li>
                <li class="layuimini-tab-roll-right layui-icon layui-icon-right"></li>
                <li class="layui-tab-tool layui-icon layui-icon-down">
                    <ul class="layui-nav close-box">
                        <li class="layui-nav-item">
                            <a href="javascript:;"><span class="layui-nav-more"></span></a>
                            <dl class="layui-nav-child">
                                <dd><a href="javascript:;" layuimini-tab-close="current">关 闭 当 前</a></dd>
                                <dd><a href="javascript:;" layuimini-tab-close="other">关 闭 其 他</a></dd>
                                <dd><a href="javascript:;" layuimini-tab-close="all">关 闭 全 部</a></dd>
                            </dl>
                        </li>
                    </ul>
                </li>
            </div>
            <div class="layui-tab-content">
                <div id="layuiminiHomeTabIframe" class="layui-tab-item layui-show">
                  <iframe src="page/dashboard.html" frameborder="0" style="width:100%;height:100%;min-height:600px;"></iframe>
                </div>
            </div>
        </div>

    </div>
</div>

<!-- AI悬浮按钮 -->
<div class="ai-float-btn" id="aiFloatBtn">
    <i class="fa fa-commenting"></i>
</div>

<!-- AI聊天窗口 -->
<div class="ai-chat-window" id="aiChatWindow">
    <div class="ai-chat-header">
        <h3><i class="fa fa-commenting"></i> AI智能助手</h3>
        <div class="ai-chat-controls">
            <span class="ai-chat-clear" title="清空对话"><i class="fa fa-trash"></i></span>
            <span class="ai-chat-close" id="aiChatClose">&times;</span>
        </div>
    </div>
    <div class="ai-chat-messages" id="aiChatMessages">
        <div class="ai-message ai">
            <div class="ai-message-content">
                <div class="message-header">
                    <i class="fa fa-commenting"></i> 智能助手
                </div>
                <div class="message-text">您好！我是智慧小区管理系统的AI助手，有什么可以帮助您的吗？</div>
                <div class="timestamp">系统消息</div>
            </div>
        </div>
    </div>
    <div class="ai-chat-input">
        <div class="ai-input-group">
            <input type="text" id="aiInput" placeholder="请输入您的问题..." maxlength="500">
            <button class="ai-send-btn" id="aiSendBtn">
                <i class="fa fa-paper-plane"></i>
            </button>
        </div>
    </div>
</div>
<script src="lib/layui-v2.6.3/layui.js" charset="utf-8"></script>
<script src="js/lay-config.js?v=2.0.0" charset="utf-8"></script>
<script>
    layui.use(['jquery', 'layer', 'miniAdmin','miniTongji'], function () {
        var $ = layui.jquery,
            layer = layui.layer,
            miniAdmin = layui.miniAdmin,
            miniTongji = layui.miniTongji;

        //如果没有登录信息
        if (!localStorage.getItem('user')) {
            layer.msg('请先登录！', {})
            setTimeout(function () {
                window.location.href = 'login.html';
            }, 1500);
        }
        // 从 localStorage 中取出整个用户对象
        const userStr = localStorage.getItem('user');
        // 转换为 JS 对象
        const user = JSON.parse(userStr);
        console.log("user:", user);
        const userid=user.user.userId;
        console.log("Sending user_id:", userid);
        $("#user_name").text(user.user.username);
        var options = {
            iniUrl: "api/init.json",    // 初始化接口
            clearUrl: "api/clear.json", // 缓存清理接口
            urlHashLocation: true,      // 是否打开hash定位
            bgColorDefault: false,      // 主题默认配置
            multiModule: true,          // 是否开启多模块
            menuChildOpen: false,       // 是否默认展开菜单
            loadingTime: 0,             // 初始化加载时间
            pageAnim: true,             // iframe窗口动画
            maxTabNum: 20,              // 最大的tab打开数量
        };
        miniAdmin.render(options);

        // 百度统计代码，只统计指定域名
        miniTongji.render({
            specific: true,
            domains: [
                '99php.cn',
                'layuimini.99php.cn',
                'layuimini-onepage.99php.cn',
            ],
        });

        $('.login-out').on("click", function () {
            layer.msg('退出登录成功', function () {
                window.location = 'login.html';
            });
        });
        
        // AI聊天功能
        var aiChatWindow = $('#aiChatWindow');
        var aiFloatBtn = $('#aiFloatBtn');
        var aiChatClose = $('#aiChatClose');
        var aiChatMessages = $('#aiChatMessages');
        var aiInput = $('#aiInput');
        var aiSendBtn = $('#aiSendBtn');
        
        // 全局变量
        var controller = null;
        var isStreaming = false;
        var currentAiMessage = null;
        
        // 拖动功能变量
        var isDragging = false;
        var isDraggingChat = false;
        var startX, startY, startLeft, startTop;
        
        // 悬浮按钮拖动功能
        aiFloatBtn.on('mousedown', function(e) {
            if (e.target.tagName === 'I') return; // 如果点击的是图标，不启动拖动
            
            isDragging = true;
            startX = e.clientX;
            startY = e.clientY;
            startLeft = parseInt(aiFloatBtn.css('left')) || 30;
            startTop = parseInt(aiFloatBtn.css('top')) || 30;
            
            aiFloatBtn.css('cursor', 'grabbing');
            e.preventDefault();
        });
        
        // 聊天窗口拖动功能
        aiChatWindow.find('.ai-chat-header').on('mousedown', function(e) {
            if (e.target.className === 'ai-chat-close') return; // 如果点击的是关闭按钮，不启动拖动
            
            isDraggingChat = true;
            startX = e.clientX;
            startY = e.clientY;
            startLeft = parseInt(aiChatWindow.css('left')) || 30;
            startTop = parseInt(aiChatWindow.css('top')) || 100;
            
            aiChatWindow.css('cursor', 'grabbing');
            e.preventDefault();
        });
        
        // 鼠标移动事件
        $(document).on('mousemove', function(e) {
            if (isDragging) {
                var newLeft = startLeft + (e.clientX - startX);
                var newTop = startTop + (e.clientY - startY);
                
                // 限制在窗口范围内
                var maxLeft = $(window).width() - aiFloatBtn.outerWidth();
                var maxTop = $(window).height() - aiFloatBtn.outerHeight();
                
                newLeft = Math.max(0, Math.min(newLeft, maxLeft));
                newTop = Math.max(0, Math.min(newTop, maxTop));
                
                aiFloatBtn.css({
                    left: newLeft + 'px',
                    top: newTop + 'px'
                });
            }
            
            if (isDraggingChat) {
                var newLeft = startLeft + (e.clientX - startX);
                var newTop = startTop + (e.clientY - startY);
                
                // 限制在窗口范围内
                var maxLeft = $(window).width() - aiChatWindow.outerWidth();
                var maxTop = $(window).height() - aiChatWindow.outerHeight();
                
                newLeft = Math.max(0, Math.min(newLeft, maxLeft));
                newTop = Math.max(0, Math.min(newTop, maxTop));
                
                aiChatWindow.css({
                    left: newLeft + 'px',
                    top: newTop + 'px'
                });
            }
        });
        
        // 鼠标释放事件
        $(document).on('mouseup', function() {
            if (isDragging) {
                isDragging = false;
                aiFloatBtn.css('cursor', 'move');
            }
            
            if (isDraggingChat) {
                isDraggingChat = false;
                aiChatWindow.css('cursor', 'default');
            }
        });
        
        // 显示/隐藏聊天窗口
        aiFloatBtn.on('click', function(e) {
            if (!isDragging) {
                if (aiChatWindow.css('display') === 'flex') {
                    aiChatWindow.hide();
                    return;
                }
                // 获取悬浮按钮的位置
                var btnLeft = parseInt(aiFloatBtn.css('left')) || 30;
                var btnTop = parseInt(aiFloatBtn.css('top')) || 30;
                var btnWidth = aiFloatBtn.outerWidth();
                var btnHeight = aiFloatBtn.outerHeight();
                
                // 计算聊天窗口的位置（在悬浮按钮附近）
                var chatWidth = 700;
                var chatHeight = 500;
                var windowWidth = $(window).width();
                var windowHeight = $(window).height();
                
                // 优先显示在悬浮按钮右侧，如果空间不够则显示在左侧
                var chatLeft = btnLeft + btnWidth + 10;
                var chatTop = btnTop;
                
                // 如果右侧空间不够，显示在左侧
                if (chatLeft + chatWidth > windowWidth) {
                    chatLeft = btnLeft - chatWidth - 10;
                }
                
                // 如果底部空间不够，向上调整
                if (chatTop + chatHeight > windowHeight) {
                    chatTop = windowHeight - chatHeight - 20;
                }
                
                // 确保不超出左边界和上边界
                chatLeft = Math.max(10, chatLeft);
                chatTop = Math.max(10, chatTop);
                
                aiChatWindow.css({
                    display: 'flex',
                    left: chatLeft + 'px',
                    top: chatTop + 'px'
                });
                aiInput.focus();
            }
        });
        
        aiChatClose.click(function() {
            aiChatWindow.hide();
        });
        
        // 添加消息到聊天窗口
        function addMessage(content, type) {
            var now = new Date();
            var timestamp = now.getHours().toString().padStart(2, '0') + ':' + now.getMinutes().toString().padStart(2, '0');
            var avatarIcon = type === 'user' ? 'fa-user' : 'fa-robot';
            var senderName = type === 'user' ? '您' : '智能助手';
            
            var messageHtml = '<div class="ai-message ' + type + '">' +
                '<div class="ai-message-content">' +
                '<div class="message-header">' +
                '<i class="fa ' + avatarIcon + '"></i> ' + senderName +
                '</div>' +
                '<div class="message-text">' + content + '</div>' +
                '<div class="timestamp">' + timestamp + '</div>' +
                '</div>' +
                '</div>';
            var messageElement = $(messageHtml);
            aiChatMessages.append(messageElement);
            aiChatMessages.scrollTop(aiChatMessages[0].scrollHeight);
            return messageElement;
        }
        
        // 停止当前回答
        function stopAnswering() {
            if (controller) {
                controller.abort();
                controller = null;
            }
            
            isStreaming = false;
            aiSendBtn.html('<i class="fa fa-paper-plane"></i>');
            aiInput.prop('disabled', false);
            
            // 添加中断消息
            if (currentAiMessage) {
                var contentDiv = currentAiMessage.find('.message-text');
                contentDiv.append('<p><i style="color: #999;">回答已停止</i></p>');
            }
        }
        
        // 发送消息
        async function sendMessage() {
            var message = aiInput.val().trim();
            if (!message || isStreaming) return;
            
            // 添加用户消息
            addMessage(message, 'user');
            aiInput.val('');
            
            // 禁用输入和发送按钮
            aiInput.prop('disabled', true);
            aiSendBtn.html('<i class="fa fa-stop"></i>').off('click').on('click', stopAnswering);
            
            try {
                // 创建AI消息容器
                currentAiMessage = addMessage('', 'ai');
                var contentDiv = currentAiMessage.find('.message-text');
                
                // 创建新的AbortController
                controller = new AbortController();
                isStreaming = true;
                console.log("Sending user_id:", userid);
                // 发送请求到后端流式API
                var response = await fetch('/ai/query', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': 'Bearer ' + user.token
                    },
                    body: JSON.stringify({
                        question: message,
                        user_id: userid,
                    }),
                    signal: controller.signal
                });
                
                if (!response.ok) {
                    throw new Error('请求失败: ' + response.status);
                }
                
                // 处理流式响应
                var reader = response.body.getReader();
                var decoder = new TextDecoder('utf-8');
                var aiResponse = '';

                while (isStreaming) {
                    var result = await reader.read();
                    if (result.done) break;

                    var chunk = decoder.decode(result.value, { stream: true });
                  //  console.log(chunk)
                    aiResponse += chunk.replace(/data:/gi, "");//.replace(/\n/g, '\u200B');
                    console.log(aiResponse)


                    // 更新AI消息内容
                    contentDiv.html(aiResponse);

                    // 滚动到最新内容
                    aiChatMessages.scrollTop(aiChatMessages[0].scrollHeight);
                }

                // 完成时添加最后的字符
                contentDiv.html(aiResponse);
                
            } catch (error) {
                if (error.name === 'AbortError') {
                    console.log('请求已被用户终止');
                } else {
                    console.error('请求出错:', error);
                    var errorDiv = $('<div style="color: #e53935;">请求出错: ' + (error.message || '服务不可用') + '</div>');
                    if (currentAiMessage) {
                        currentAiMessage.find('.message-text').append(errorDiv);
                    } else {
                        addMessage(errorDiv.prop('outerHTML'), 'ai');
                    }
                }
            } finally {
                // 重置状态
                isStreaming = false;
                aiSendBtn.html('<i class="fa fa-paper-plane"></i>').off('click').on('click', sendMessage);
                aiInput.prop('disabled', false);
                controller = null;
                
                // 聚焦到输入框
                aiInput.focus();
            }
        }
        // 清空对话
        function clearConversation() {
            aiChatMessages.html('<div class="ai-message ai">' +
                '<div class="ai-message-content">' +
                '<div class="message-header">' +
                '<i class="fa fa-robot"></i> 智能助手' +
                '</div>' +
                '<div class="message-text">对话已重置！您可以开始新的提问。</div>' +
                '<div class="timestamp">系统消息</div>' +
                '</div>' +
                '</div>');
        }
        
        // 发送按钮点击事件
        aiSendBtn.on('click', sendMessage);
        
        // 回车键发送消息
        aiInput.keypress(function(e) {
            if (e.which === 13 && !e.shiftKey) {
                e.preventDefault();
                sendMessage();
            }
        });
        
        // 添加清空按钮事件（如果需要的话）
        // 可以在聊天窗口头部添加一个清空按钮
        // aiChatWindow.find('.ai-chat-header').append('<span class="ai-chat-clear" style="margin-right: 10px; cursor: pointer;" title="清空对话"><i class="fa fa-trash"></i></span>'); // This line is removed as per the edit hint
        aiChatWindow.find('.ai-chat-clear').click(clearConversation);
    });
</script>
</body>
</html>
